package com.example.socialapp.ui.auth.login

import androidx.lifecycle.viewModelScope
import com.example.socialapp.domain.usecase.auth.LoginUseCase
import com.example.socialapp.ui.base.mvi.MviViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject

/**
 * ViewModel for the login screen
 */
@HiltViewModel
class LoginViewModel @Inject constructor(
    private val loginUseCase: LoginUseCase
) : MviViewModel<LoginState, LoginIntent, LoginEffect>() {

    override fun createInitialState(): LoginState = LoginState()

    override fun processIntent(intent: LoginIntent) {
        when (intent) {
            is LoginIntent.UpdateEmail -> updateEmail(intent.email)
            is LoginIntent.UpdatePassword -> updatePassword(intent.password)
            is LoginIntent.ToggleRememberMe -> toggleRememberMe(intent.rememberMe)
            is LoginIntent.SubmitLogin -> submitLogin()
            is LoginIntent.NavigateToRegister -> navigateToRegister()
            is LoginIntent.NavigateToForgotPassword -> navigateToForgotPassword()
            is LoginIntent.LoginWithGoogle -> loginWithGoogle()
            is LoginIntent.LoginWithFacebook -> loginWithFacebook()
            is LoginIntent.LoginWithApple -> loginWithApple()
        }
    }

    /**
     * Update email field
     *
     * @param email New email value
     */
    private fun updateEmail(email: String) {
        updateState { it.copy(
            email = email,
            isEmailError = false,
            emailErrorMessage = ""
        ) }
    }

    /**
     * Update password field
     *
     * @param password New password value
     */
    private fun updatePassword(password: String) {
        updateState { it.copy(
            password = password,
            isPasswordError = false,
            passwordErrorMessage = ""
        ) }
    }

    /**
     * Toggle remember me checkbox
     *
     * @param rememberMe New remember me value
     */
    private fun toggleRememberMe(rememberMe: Boolean) {
        updateState { it.copy(rememberMe = rememberMe) }
    }

    /**
     * Submit login form
     */
    private fun submitLogin() {
        val currentState = state.value
        val email = currentState.email
        val password = currentState.password
        val rememberMe = currentState.rememberMe

        // Set loading state
        updateState { it.copy(isLoading = true) }
        
        viewModelScope.launch {
            loginUseCase(email, password, rememberMe)
                .onSuccess { user ->
                    Timber.d("Login successful for user: ${user.email}")
                    updateState { it.copy(isLoading = false) }
                    emitEffect(LoginEffect.ShowSuccess("Login successful"))
                    emitEffect(LoginEffect.NavigateToMain)
                }
                .onFailure { error ->
                    Timber.e(error, "Login failed")
                    
                    when (error) {
                        is IllegalArgumentException -> {
                            when {
                                error.message?.contains("Email") == true -> {
                                    updateState { it.copy(
                                        isLoading = false,
                                        isEmailError = true,
                                        emailErrorMessage = error.message ?: "Invalid email"
                                    ) }
                                }
                                error.message?.contains("Password") == true -> {
                                    updateState { it.copy(
                                        isLoading = false,
                                        isPasswordError = true,
                                        passwordErrorMessage = error.message ?: "Invalid password"
                                    ) }
                                }
                                else -> {
                                    updateState { it.copy(isLoading = false) }
                                    emitEffect(LoginEffect.ShowError(error.message ?: "Login failed"))
                                }
                            }
                        }
                        else -> {
                            updateState { it.copy(isLoading = false) }
                            emitEffect(LoginEffect.ShowError(error.message ?: "Login failed"))
                        }
                    }
                }
        }
    }

    /**
     * Navigate to register screen
     */
    private fun navigateToRegister() {
        emitEffect(LoginEffect.NavigateToRegister)
    }

    /**
     * Navigate to forgot password screen
     */
    private fun navigateToForgotPassword() {
        emitEffect(LoginEffect.NavigateToForgotPassword)
    }

    /**
     * Login with Google
     */
    private fun loginWithGoogle() {
        emitEffect(LoginEffect.LaunchGoogleSignIn)
    }

    /**
     * Login with Facebook
     */
    private fun loginWithFacebook() {
        emitEffect(LoginEffect.LaunchFacebookSignIn)
    }

    /**
     * Login with Apple
     */
    private fun loginWithApple() {
        emitEffect(LoginEffect.LaunchAppleSignIn)
    }
} 